﻿using System;
using System.Linq;

namespace BLL
{
  
    public class [tblName] : baseBLL
    {
  

        public Data.[tblName] GetById(int id)
        {
            var db = new Data.DataEntities();
            var model = db.[tblName].FirstOrDefault(p => p.id == id);
            return model;
        }

        public bool Delete(int id)
        {
            int rows = 0;
            var db = new Data.DataEntities();
            var model = db.[tblName].FirstOrDefault(p => p.id == id);
            if (model != null)
            {
                db.[tblName].Remove(model);
                rows = db.SaveChanges();
            }
            return rows > 0;
        }

        public int Update(Data.[tblName] viewModel)
        {
            var db = new Data.DataEntities();
            if (viewModel.id <= 0)
            {
                db.[tblName].Add(viewModel);
            }
            else
            {
                var mod = db.[tblName].FirstOrDefault(p => p.id == viewModel.id);
                mod = Mapper(viewModel, mod);
            }
            var rows = db.SaveChanges();
            return rows;
            
        }

        public Pager List(System.Collections.Generic.Dictionary<string,string> dic)
        {
            int pageindex = 1, pagesize = 100000;
            if (dic.ContainsKey("pageindex")) int.TryParse(dic["pageindex"], out pageindex);
            if (dic.ContainsKey("pagesize")) int.TryParse(dic["pagesize"], out pagesize);
            if (pageindex <= 0) pageindex = 1;

            int total = 0;
            var db = new Data.DataEntities();
            var list = from p in db.[tblName]
                       select new
                       {
  [loop start]
                           p.[fldName],
  [loop end]^
                           p.id

                       };
            //此处加条件
            int id = 0;
            if (dic.ContainsKey("id"))
            {
                id = Convert.ToInt32(dic["id"]);
                list = list.Where(p => p.id == id);
            }

            list = list.OrderByDescending(p => p.id);
            total = list.ToList().Count();
            list = list.Skip((pageindex - 1) * pagesize).Take(pagesize);
            return new Pager(list, total);

        }
        
    }
}
